package com.medicine.manage.block.service;

import com.medicine.manage.block.WeBASEUtils;
import com.medicine.manage.block.entity.WeBaseResult;
import com.medicine.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public abstract class AbstractBlockService<T> implements IBlockService<T>{

    @Autowired
    private IUserExtendService userExtendService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private WeBASEUtils weBASEUtils;


    @Override
    public WeBaseResult insertOne(T obj, Long deptId, Long optionUserId, String functionName) {
        String contractAddress = deptService.getContractAddress(deptId);
        // 查询该操作员的address
        String userName = userExtendService.getSignUserName(optionUserId);
        // 准备智能合约订单插入方法所需参数
        List<String> list = new ArrayList<>();
        String param = this.createParam(obj, optionUserId);
        list.add(param);

        String string = weBASEUtils.funcPost(userName,contractAddress,functionName, list);
        WeBaseResult weBaseResult = weBASEUtils.convertResult(string);
        return weBaseResult;
    }

    @Override
    public WeBaseResult selectOne(Long orderId, Long id, Long deptId, Long optionUserId, String functionName) {

        String contractAddress = deptService.getContractAddress(deptId);
        String userName = userExtendService.getSignUserName(optionUserId);
        List<String> list = new ArrayList<>();

        list.add(orderId.toString());
        list.add(id.toString());

        String string = weBASEUtils.funcPost(userName,contractAddress, functionName, list);
        WeBaseResult result = weBASEUtils.convertViewResult(string);

        return result;
    }

    @Override
    public WeBaseResult update(Long orderId, T obj, Long deptId, Long optionUserId, String functionName) {
        // 查询该煎药机构的合约address
        String contractAddress = deptService.getContractAddress(deptId);
        // 查询该操作员的address
        String userName = userExtendService.getSignUserName(optionUserId);
        // 准备智能合约订单插入方法所需参数
        List<String> list = new ArrayList<>();
        String param = this.createParam(obj, optionUserId);
        list.add(String.valueOf(orderId));
        list.add(param);

        String string = weBASEUtils.funcPost(userName,contractAddress,functionName, list);
        WeBaseResult weBaseResult = weBASEUtils.convertResult(string);
        return weBaseResult;
    }

    protected abstract String createParam(T o, Long optionUserId);
}
